package servlet;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//JAXP
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Source;
import javax.xml.transform.Result;
import javax.xml.transform.sax.SAXResult;

//FOP
import org.apache.fop.servlet.ServletContextURIResolver;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.MimeConstants;

public class PDFController extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private FopFactory fopFactory;
    private TransformerFactory tFactory;
    protected ServletContextURIResolver uriResolver;

    /**
     * Constructor of the object.
     */
    public PDFController() {
        super();
    }

    public void destroy() {
        super.destroy();
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String realPath = getServletContext().getRealPath("/");
        try {
            String albumId = request.getParameter("albumID");
            FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
            foUserAgent.setBaseURL("file:///" + realPath);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            fopFactory.setURIResolver(uriResolver);
            Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);
            Source xsltSrc = this.uriResolver.resolve(
                    "servlet-context:/WEB-INF/albumDetailFO.xsl", null);
            tFactory.setURIResolver(uriResolver);
            Transformer transformer = tFactory.newTransformer(xsltSrc);
            transformer.setURIResolver(uriResolver);
            Result res = new SAXResult(fop.getDefaultHandler());
            Source xmlSrc = uriResolver.resolve(
                    "servlet-context:/WEB-INF/album-" + String.valueOf(albumId) + ".xml", null);
            transformer.transform(xmlSrc, res);
            response.setContentType("application/pdf");
            response.setContentLength(out.size());
            response.getOutputStream().write(out.toByteArray());
            response.getOutputStream().flush();
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

    public void init() throws ServletException {
        uriResolver = new ServletContextURIResolver(getServletContext());
        fopFactory = FopFactory.newInstance();
        tFactory = TransformerFactory.newInstance();
    }
}
